package fr.lip6.meta.ple.plextraction;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.eclipse.java.generation.FeatureToCode;

import test.popup.actions.JavaDiscover;

import artefact.generic.Artefact;

import fr.lip6.meta.ple.constraintsextraction.constraint.Constraint;
import fr.lip6.meta.ple.featureIdentification.Feature;
import fr.lip6.meta.ple.featureIdentification.Product;
import fr.lip6.meta.ple.featureIdentification.SiFeatureExtraction;
import fr.lip6.meta.tools.ModelXML;



public class Extract {
	public static String nameTestCase="";
	public static String[] products;

	public static void extract(
			ArrayList<Artefact> artfacts, 
			String nameTestCase1, 
			String[] products1,
			String outputfolder){
 

		nameTestCase=nameTestCase1;
		products=products1;
		
		for(Artefact ar : artfacts){
			Artefact2File.print(ar,nameTestCase1+"/Product"+"_"+ar.getId());
		}
		
		SiFeatureExtraction sif = new SiFeatureExtraction();
		Collection<Feature> si_features = sif.extract(artfacts);
		try {
			sif.featuresToFile(nameTestCase1+"/SI_features.txt");
		} catch (Exception e) {
			e.printStackTrace();
		}


		Collection<Product> si_products=sif.getAllP();
		//System.out.println("Generating product");
		//new GenerateFromXmiFHJava();
		//new CompareMethode();
		
		//System.err.println("Number of features: "+si_features.size());
		//ProductLineConstructionFHJava pr=new ProductLineConstructionFHJava();
		ModelXML mod = new ModelXML();
		mod.setProducts(si_products);
		mod.generateFeatureModel(si_features, new ArrayList<Constraint>(), outputfolder);

		JavaDiscover discover=new JavaDiscover();
		ArrayList<Feature> myfs = new ArrayList<Feature>();
		for (Feature f: si_features) myfs.add(f);
		
		for (Feature f: myfs) 
		{
			//System.out.println ("@@@@@@ Printing Feature :"+f.getId()+ " @@@@@@");
			//System.out.println (f.toString());
			//System.out.println ("@@@@@@ End  @@@@@");
			FeatureToCode.init(f);
			if(f.getIdAnc() != null) {
				int i = Integer.parseInt(f.getIdAnc().split("F")[1]);
				FeatureToCode.getAllClassNamesInFeatureBase(myfs.get(i));
			}
			Iterator<Integer> p = f.getProdIds().iterator();
			int product = 1;
			//System.err.println("---------------------------");
			//System.err.println("Product :"+products[product]);
			//System.err.println("---------------------------");

			if(p.hasNext())
				product =	p.next();

			if(f.getId().split("_").length>2)
				discover.generateJava(products1[product],outputfolder+"/"+f.getName());
			else
				discover.generateJava(products1[product],outputfolder+"/"+f.getId());
		}
	}

}
